import redis
import json
import datetime

class RealTimeView(object):

    def __init__(self, address, port, db=0, password=None):

        print("Connecting Database")
        self.address = address
        self.port = port
        self.username = "admin"
        self.password = password
        #
        pool = redis.ConnectionPool(host=address, port=port, db=db)
        self.instance = redis.Redis(connection_pool=pool)


    #---Push to Realtime View---
    def SetDocument(self, key, document):
        #
        if "_id" in document:
            del document["_id"]
        for k,v in document.items():
            document[k] = str(document[k])

        #
        s = json.dumps(document)
        self.instance.set(key, s)


    def Set(self, key, document):
        s = json.dumps(document)
        self.instance.set(key, s)


    #---Read from Realtime View---
    def Read(self, key):
        j = self.instance.get(key)
        if j == None:
            return
        s = str(j, encoding = "utf-8")
        jsonObj = json.loads(s)
        return jsonObj
        #documment = OptionPricer.OptionPricer.Deserializer(jsonObj)


    def MultiSet(self, dict):
        self.instance.mset(dict)


    def MultiGet(self, pattern):
        return self.instance.keys(pattern + "*")


    def Get(self, key):
        return self.Read(key)


    def SetHashList(self, name, dic):
        for key, value in dic.items():
            s = json.dumps(value)
            self.SetHash(name, key, s)

    def GetHashList(self, name):
        dic = {}
        keys = self.instance.hkeys(name)
        for key in keys:
            dic[key] = self.GetHashDoc(name,key)

        return dic


    def SetHashDoc(self, name, key, document):
        if "_id" in document:
            del document["_id"]
        for k,v in document.items():
            document[k] = str(document[k])
        s = json.dumps(document)
        self.instance.hset(name, key, s)


    def GetHashDoc(self, name, key):
        value = self.instance.hget(name, key)
        s = str(value, encoding="utf-8")
        jsonObj = json.loads(s)
        return jsonObj


    def SetHash(self, name, key, value):
        self.instance.hset(name, key, value)


    def GetHash(self, name, key, value):
        self.instance.hset(name, key, value)


    def Clear(self):
        self.instance.flushdb()


    def Delete(self,key):
        self.instance.delete(key)


    def Publish(self, channel, message):
        self.instance.publish(channel, message)


    def Subscribe(self, channel):
        pubsub = self.instance.pubsub()
        pubsub.subscribe(channel)

        while(True):
            pubsub.listen()
            msg = pubsub.parse_response()
            print("Received @" + str(datetime.datetime.now()) + " " + str(msg))





